<!--
 * @Description: 编辑场地
 * @Author: xiao li
 * @Date: 2021-12-22 11:28:58
 * @LastEditTime: 2022-01-26 15:52:41
 * @LastEditors: xiao li
-->
<template>
  <div class="lb-car-article-edit">
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="subForm"
        label-width="120px"
      >
        <el-form-item label="场地名称" prop="title">
          <el-input
            v-model="subForm.title"
            placeholder="请输入场地名称"
            maxlength="10"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="场地面积" prop="area">
          <el-input v-model="subForm.area" placeholder="请输入场地面积"
            ><template slot="append">㎡</template></el-input
          >
        </el-form-item>
        <el-form-item label="容纳桌数" prop="num">
          <el-input
            style="width: 114px"
            v-model.number="subForm.min_num"
          ></el-input>
          <block>-</block>
          <el-input style="width: 168px" v-model.number="subForm.max_num"
            ><template slot="append">桌</template></el-input
          >
        </el-form-item>
        <el-form-item label="层高" prop="floor">
          <el-input v-model="subForm.floor" placeholder="请输入层高"
            ><template slot="append">m</template></el-input
          >
        </el-form-item>
        <el-form-item label="立柱" prop="column">
          <el-input v-model="subForm.column" placeholder="请输入立柱"
            ><template slot="append">根</template></el-input
          >
        </el-form-item>
        <el-form-item label="形状" prop="shape">
          <el-input
            v-model="subForm.shape"
            placeholder="请输入形状，例如：长方形"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格面议" prop="price_face">
          <el-radio-group v-model="subForm.price_face">
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="预付金"
          prop="price"
          v-if="subForm.price_face === 0"
        >
          <el-input v-model="subForm.price" placeholder="请输入预付金">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="价格备注" prop="des">
          <el-input
            v-model="subForm.des"
            placeholder="请输入价格备注"
            maxlength="20"
            show-word-limit
          ></el-input>
          <lb-tool-tips
            >填写之后，备注将会体现在小程序端选择预约时间的弹窗里，不填写则没有</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="所属公司" prop="company_id">
          <el-select
            v-model="subForm.company_id"
            filterable
            placeholder="请选择所属公司"
          >
            <el-option
              v-for="item in base_company"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宴席套餐" prop="package">
          <el-select
            v-model="subForm.package"
            multiple
            filterable
            clearable
            collapse-tags
            placeholder="请选择宴席套餐"
          >
            <el-option
              v-for="item in base_package"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预订信息" prop="content">
          <el-select
            v-model="subForm.content"
            multiple
            filterable
            clearable
            collapse-tags
            placeholder="请选择预订信息"
          >
            <el-option
              v-for="item in base_content"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            @selectedFiles="getCover($event, 'cover')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 200 * 200</lb-tool-tips>
        </el-form-item>
        <el-form-item label="轮播图" prop="imgs">
          <lb-cover
            type="more"
            :fileList="subForm.imgs"
            @selectedFiles="selectedFiles($event, 'imgs')"
            @moveFiles="moveFiles($event, 'imgs')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸：750 * 520</lb-tool-tips>
        </el-form-item>
        <el-form-item label="轮播图链接" prop="link">
          <el-input
            v-model="subForm.link"
            placeholder="请输入轮播图跳转链接"
          ></el-input>
          <lb-tool-tips>点击轮播图跳转到对应链接</lb-tool-tips>
        </el-form-item>
        <el-form-item label="VR封面" prop="vr_cover">
          <lb-cover
            :fileList="subForm.vr_cover"
            @selectedFiles="getCover($event, 'vr_cover')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 520</lb-tool-tips>
        </el-form-item>
        <el-form-item label="VR链接" prop="vr">
          <el-input
            v-model="subForm.vr"
            placeholder="请输入VR跳转链接"
          ></el-input>
          <lb-tool-tips>点击VR封面跳转到对应VR链接</lb-tool-tips>
        </el-form-item>
        <el-form-item label="视频封面" prop="video_cover">
          <lb-cover
            :fileList="subForm.video_cover"
            @selectedFiles="getCover($event, 'video_cover')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 520</lb-tool-tips>
        </el-form-item>
        <el-form-item label="视频链接" prop="video">
          <div class="item-warp">
            <div class="upload-file-warp">
              <input
                type="text"
                class="choice-file-input"
                v-model="subForm.video"
                placeholder="请输入视频链接或选择视频文件"
              />
              <lb-cover
                type="button"
                fileType="video"
                @selectedFiles="getVideo"
              ></lb-cover>
            </div>
            <lb-tool-tips>点击视频封面可播放视频</lb-tool-tips>
          </div>
        </el-form-item>
        <el-form-item label="档期设置" prop="date">
          <div class="flex-y-center">
            <div
              @click="toCheckAll"
              class="flex-y-center"
              :class="[{ 'c-link': isAll }]"
              style="cursor: pointer"
            >
              <i
                class="iconfont mr-sm"
                :class="[
                  { iconyduifuxuankuang: !isAll },
                  {
                    iconyduifuxuankuangxuanzhong: isAll
                  }
                ]"
              ></i>
              <div class="f-desc">全选</div>
            </div>
            <el-tag
              @click="toShowDialog(1)"
              class="ml-lg"
              style="cursor: pointer"
              >批量编辑</el-tag
            ><el-tag
              @click="toShowDialog(2)"
              type="danger"
              class="ml-lg mr-lg"
              style="cursor: pointer"
              >批量删除</el-tag
            >
            <el-date-picker
              :clearable="false"
              @change="getDayArr(2)"
              v-model="timeValue"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </div>
          <el-calendar v-model="timeValue">
            <template slot="dateCell" slot-scope="{ date, data }">
              <div @click.stop="toCheck(date, data)" class="calendar-item rel">
                <div class="f-paragraph abs" style="top: 2px; right: 0px">
                  {{ data.day.split('-').slice(2).join('-') }}
                </div>
                <block v-for="(item, index) in dayArr" :key="index">
                  <block
                    v-if="
                      item.month ===
                      data.day.substring(0, data.day.lastIndexOf('-'))
                    "
                  >
                    <block v-for="(aitem, aindex) in item.list" :key="aindex">
                      <div v-if="aitem.date === data.day" style="height: 69px">
                        <div class="flex-y-center">
                          <block v-if="data.type === 'current-month'">
                            <i
                              class="iconfont"
                              :class="[
                                { iconyduifuxuankuang: !aitem.is_check },
                                {
                                  'iconyduifuxuankuangxuanzhong c-link':
                                    aitem.is_check
                                }
                              ]"
                              v-if="
                                aitem.status === 1 || curTime - 1 < aitem.time
                              "
                            ></i>
                            <i
                              @click.stop="toShowDialog(3, index, aindex)"
                              class="iconfont iconbianji1 ml-sm"
                              v-if="curTime - 1 < aitem.time"
                            ></i>
                            <i
                              @click.stop="confirmDel(2, index, aindex)"
                              class="iconfont icon-del ml-sm c-warning"
                              v-if="aitem.status === 1"
                            ></i
                          ></block>
                        </div>
                        <div v-if="aitem.status === 1">
                          <div
                            class="flex-y-center c-title ellipsis"
                            style="margin-top: 8px; font-size: 12.5px"
                          >
                            <div
                              class="dot radius"
                              style="background: #e6a23c"
                              v-if="aitem.title"
                            ></div>
                            {{ aitem.title }}
                          </div>
                          <div class="flex-y-center f-caption c-caption">
                            <div
                              class="dot radius"
                              style="background: #409eff"
                            ></div>
                            {{ `中: ${aitem.noon_price}` }}
                          </div>
                          <div
                            class="flex-y-center f-caption c-caption"
                            v-if="aitem.night_price"
                          >
                            <div
                              class="dot radius"
                              style="background: #f56c6c"
                            ></div>
                            {{ `晚: ${aitem.night_price}` }}
                          </div>
                        </div>
                      </div>
                    </block>
                  </block>
                </block>
              </div>
            </template>
          </el-calendar>
        </el-form-item>
        <el-form-item label="场地说明" prop="text">
          <lb-ueditor v-model="subForm.text" :destroy="true"></lb-ueditor>
        </el-form-item>
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.top"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitFormInfo">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="$router.go(-1)">{{ $t('action.back') }}</lb-button>
        </el-form-item>
      </el-form>

      <el-dialog
        :title="dialogForm.type === 1 ? '批量编辑档期' : '编辑档期'"
        :visible.sync="showDialog"
        width="500px"
        center
      >
        <el-form
          class="dialog-form"
          :model="dialogForm"
          ref="dialogForm"
          :rules="dialogFormRules"
          label-width="100px"
        >
          <el-form-item label="日子说明" prop="title">
            <el-input
              v-model="dialogForm.title"
              maxlength="4"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="中午价格" prop="noon_price">
            <el-input
              v-model="dialogForm.noon_price"
              placeholder="请输入中午价格"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="晚上价格" prop="night_price">
            <el-input
              v-model="dialogForm.night_price"
              placeholder="请输入晚上价格"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitDialogFormInfo"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reg } from '@/utils/reg'
export default {
  data () {
    let validateNum = (rule, value, callback) => {
      let { min_num: min, max_num: max } = this.subForm
      if (!min || !max) {
        callback(new Error(!min ? `请输入最小容纳桌数` : `请输入最大容纳桌数`))
      } else if (!/^\+?[0-9]*$/.test(min) || !/^\+?[0-9]*$/.test(max)) {
        callback(new Error(!/^\+?[0-9]*$/.test(min) ? `请输入正确的最小容纳桌数` : `请输入正确的最大容纳桌数`))
      } else if (min * 1 + 1 > max * 1) {
        callback(new Error(`最大容纳桌数必须大于最小容纳桌数`))
      } else {
        callback()
      }
    }
    let validatePrice = (rule, value, callback) => {
      let reg = /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
      if (this.subForm.price_face === 1) {
        callback()
      } else if (!value) {
        callback(new Error(`请输入预付金额`))
      } else if (!reg.test(value)) {
        callback(new Error(`请输入正确的金额，最多保留两位小数`))
      } else {
        callback()
      }
    }
    return {
      options: [],
      value: [],
      loading: false,
      navTitle: '',
      base_company: [],
      base_package: [],
      base_content: [],
      curTime: '',
      timeValue: new Date(),
      curDate: '',
      dayArr: [],
      subForm: {
        id: 0,
        title: '',
        area: '',
        min_num: '',
        max_num: '',
        floor: '',
        column: '',
        shape: '',
        price: '',
        price_face: 0,
        des: '',
        company_id: '',
        package: [],
        cover: [],
        imgs: [],
        link: '',
        vr_cover: [],
        vr: '',
        video_cover: [],
        video: '',
        text: '',
        top: 0
      },
      subFormRules: {
        title: { required: true, validator: reg.isNotNull, text: '场地名称', reg_type: 2, trigger: 'blur' },
        area: { required: true, validator: reg.valiDateFloat, text: '面积', trigger: 'blur' },
        num: { required: true, validator: validateNum, trigger: 'blur' },
        floor: { required: true, validator: reg.valiDateFloat, text: '层高', trigger: 'blur' },
        column: { required: true, validator: reg.isNum, text: '立柱', reg_type: 2, trigger: 'blur' },
        shape: { required: true, validator: reg.isNotNull, text: '形状', reg_type: 2, trigger: 'blur' },
        price_face: { required: true, type: 'number', message: '请选择价格面议', trigger: 'blur' },
        price: { required: true, validator: validatePrice, trigger: 'blur' },
        company_id: { required: true, type: 'number', message: '请选择所属公司', trigger: 'blur' },
        package: { required: true, type: 'array', message: '请选择宴席套餐', trigger: 'blur' },
        content: { required: true, type: 'array', message: '请选择预订信息', trigger: 'blur' },
        cover: { required: true, type: 'array', message: '请上传封面图', trigger: 'blur' },
        imgs: { required: true, type: 'array', message: '请上传轮播图', trigger: 'blur' },
        text: { required: true, type: 'string', message: '请输入场地说明', trigger: 'blur' },
        top: { required: true, type: 'number', message: '请输入排序值', trigger: 'blur' }
      },
      isAll: false,
      showDialog: false,
      dialogForm: {
        id: 0,
        title: '',
        noon_price: '',
        night_price: ''
      },
      dialogFormRules: {
        noon_price: { required: true, validator: reg.isMoney, text: '中午价格', reg_type: 1, max_num: 999999.99, trigger: 'blur' }
      }
    }
  },
  async created () {
    let { id = 0 } = this.$route.query
    this.subForm.id = id
    this.navTitle = this.$t(id ? 'menu.BanquetFieldEdit' : 'menu.BanquetFieldAdd')
    await this.getBaseInfo()

    this.$nextTick(() => {
      // 点击前一个月
      let prevBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(1)"
      );
      prevBtn.addEventListener("click", e => {
        this.getDayArr()
      })
      //点击下一个月
      let nextBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(3)"
      );
      nextBtn.addEventListener("click", e => {
        this.getDayArr()
      })
      //点击今天
      let todayBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(2)"
      );
      todayBtn.addEventListener("click", e => {
      })
    })

    if (!id) return
    this.getDetail()
  },
  methods: {
    async getBaseInfo () {
      this.curTime = moment(moment(new Date().getTime()).format('YYYY-MM-DD')).unix()
      let [company, cate, content] = await Promise.all([this.$api.getBaseCompany(), this.$api.banquet.packageSelect(), this.$api.banquet.contentSelect(), this.getDayArr(1)])
      this.base_company = company.data
      this.base_package = cate.data
      this.base_content = content.data
    },
    async getDayArr (type = 2) {
      let { id } = this.subForm
      let date = type === 1 ? moment(new Date().getTime()).format('YYYY-MM') : moment(new Date(this.timeValue).getTime()).format('YYYY-MM')
      if (this.curDate === date) return
      this.curDate = date
      this.isAll = false
      this.dayArr.map(item => {
        item.list.map(aitem => {
          aitem.is_check = false
        })
      })
      let index = this.dayArr.findIndex(item => {
        return item.month === date
      })
      if (index > -1) return
      let { code, data } = await this.$api.banquet.monthDateList({ date, place_id: id })
      if (code !== 200) return
      data.map(item => {
        item.title = item.title || ''
        item.noon_price = item.noon_price || ''
        item.night_price = item.night_price || ''
        item.status = item.status || 0
      })
      this.dayArr.push({ month: date, list: data })
    },
    async getDetail () {
      let { id } = this.subForm
      let { code, data } = await this.$api.banquet.placeInfo({
        id
      })
      if (code !== 200) return
      let imgs = ['cover', 'vr_cover', 'video_cover']
      imgs.map(item => {
        data[item] = data[item] && data[item].length > 0 ? [{ url: data[item] }] : []
      })
      data.imgs = data.imgs.map(item => { return { url: item } })
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
    },
    getCover (img, key) {
      this.subForm[key] = img
    },
    selectedFiles (imgs, key) {
      this.subForm[key].push(...imgs)
    },
    moveFiles (imgs, key) {
      this.subForm[key] = imgs
    },
    getVideo (video) {
      this.subForm.video = video[video.length - 1].url
    },
    toCheck (date, data) {
      let { day, type } = data
      let month = day.substring(0, day.lastIndexOf('-'))
      if (type !== 'current-month') {
        this.timeValue = date
        this.getDayArr()
        return
      }
      let dayArr = JSON.parse(JSON.stringify(this.dayArr))
      let index = dayArr.findIndex(item => {
        return item.month === month
      })
      dayArr[index].list.map(item => {
        if (item.date === day) {
          item.is_check = !item.is_check
        }
      })
      this.dayArr = dayArr
    },
    toCheckAll () {
      let { isAll, curDate } = this
      let dayArr = JSON.parse(JSON.stringify(this.dayArr))
      let ind = dayArr.findIndex(item => {
        return curDate === item.month
      })
      dayArr[ind].list.filter(item => {
        item.is_check = !isAll
      })
      this.dayArr = dayArr
      this.isAll = !isAll
    },
    /**
     * @name: 编辑/删除
     * @param {*} type 1批量编辑，2批量删除，3编辑
     * @param {*} index
     * @param {*} aindex
     */
    toShowDialog (type, index, aindex) {
      let item = {
        title: '',
        noon_price: '',
        night_price: '',
        type
      }
      if (type === 1 || type === 2) {
        let { curDate, dayArr } = this
        let ind = dayArr.findIndex(item => {
          return curDate === item.month
        })
        if (type === 2) {
          let arr = dayArr[ind].list.filter(item => {
            return item.status === 1
          })
          if (arr.length === 0) {
            this.$message.error(`没有数据可删除`)
            return
          }
        }
        let arr = dayArr[ind].list.filter(item => {
          return item.is_check
        })
        if (arr.length === 0) {
          this.$message.error(`请选择数据后再批量操作`)
          return
        }
        if (type === 2) {
          let data = arr.filter(item => {
            return item.status === 1
          })
          if (data.length === 0) {
            this.$message.error(`没有数据可删除`)
            return
          }
          this.confirmDel(1, ind)
          return
        }
      } else {
        item = JSON.parse(JSON.stringify(this.dayArr[index].list[aindex]))
        item.index = index
        item.aindex = aindex
        item.type = type
      }
      this.dialogForm = item
      this.showDialog = true
    },
    /**
     * @method: 删除
     * @param {*} type 1批量删除，2删除
     * @param {*} index
     * @param {*} aindex
     */
    confirmDel (type, index, aindex) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        let dayArr = JSON.parse(JSON.stringify(this.dayArr))
        if (type === 1) {
          dayArr[index].list.map(item => {
            if (item.is_check) {
              item.title = ''
              item.noon_price = ''
              item.night_price = ''
              item.status = 0
            }
          })
        } else {
          dayArr[index].list[aindex].title = ''
          dayArr[index].list[aindex].noon_price = ''
          dayArr[index].list[aindex].night_price = ''
          dayArr[index].list[aindex].status = 0
        }
        this.dayArr = dayArr
      })
    },
    /**
     * @name: 编辑档期
     * @param {*}
     */
    submitDialogFormInfo () {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          let item = JSON.parse(JSON.stringify(this.dialogForm))
          let reg = /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
          if (item.night_price && !reg.test(item.night_price)) {
            this.$message.error(`请输入正确的金额，最多保留2位小数`)
            return
          }
          if (item.night_price && item.night_price * 1 > 999999.99) {
            this.$message.error(`请输入正确的金额，不能大于999999.99`)
            return
          }
          let dayArr = JSON.parse(JSON.stringify(this.dayArr))
          let { title, noon_price: noon, night_price: night, index, aindex, type } = item
          let { curTime, curDate } = this
          if (type === 1) {
            let ind = dayArr.findIndex(item => {
              return curDate === item.month
            })
            dayArr[ind].list.filter(item => {
              if (curTime - 1 < item.time && item.is_check) {
                item.title = title
                item.noon_price = noon
                item.night_price = night
                item.status = 1
              }
            })
          } else {
            delete item.index
            delete item.aindex
            delete item.type
            item.status = 1
            dayArr[index].list[aindex] = item
          }
          this.dayArr = dayArr
          this.showDialog = false
        }
      })
    },
    submitFormInfo () {
      this.$refs['subForm'].validate(valid => {
        if (valid) {
          let subForm = JSON.parse(JSON.stringify(this.subForm))
          let imgs = ['cover', 'vr_cover', 'video_cover']
          imgs.map(item => {
            subForm[item] = subForm[item] && subForm[item].length > 0 ? subForm[item][0].url : ''
          })
          subForm.imgs = subForm.imgs.map(item => {
            return item.url
          })
          let arr = []
          this.dayArr.map(item => {
            item.list.map(aitem => {
              // if (this.curTime - 1 < aitem.time) {
              arr.push(aitem)
              // }
            })
          })
          subForm.date = arr
          subForm.price = subForm.price_face === 1 ? 0 : subForm.price
          let methodModel = subForm.id ? 'placeUpdate' : 'placeAdd'
          this.$api.banquet[methodModel](subForm).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
              this.$router.back(-1)
            }
          })
        }
      })
    }
  },
  watch: {
    'subForm.text' (newValue, oldValue) {
      if (newValue && !oldValue) {
        this.$refs['subForm'].clearValidate('text')
      }
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-car-article-edit {
  width: 100%;

  .el-input,
  .el-input-number,
  .el-select {
    width: 300px;
  }

  .mini {
    width: 120px;
  }

  .el-textarea {
    width: 600px;
  }
  .calendar-item {
    div {
      height: 16px;
      line-height: 1;
    }
    .dot {
      width: 6px;
      height: 6px;
      margin-right: 3px;
    }
  }
}
</style>
